package com.sun.service;/**
 * @author sun
 * @date 2022/1/4 - 11:35
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @description: 自定义登录逻辑
 * @author 孙
 * @date 2022/1/4 11:35
 * @version 1.0
 */
@Configuration
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("23222222222222222222222222");
        //查询数据库，判断用户名是否存在，用户名不存在会抛出UsernameNotFoundException异常
        if(!"admin".equals(username)){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //把查询出来的密码（注册时已经加密过）进行解析，或者直接把密码放入构造方法
        String password=passwordEncoder.encode("123456");
        //返回用户对象,给角色赋权和分配角色
        return new User("admin", password,
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin," +
                        "normal,ROLE_abc,/main.html, /insert, /delete"));

    }
}
